<?php

namespace app\api\controller;
use think\facade\Db;
use think\facade\Env;
use app\admin\model\Customer as CustomerModel;

 
class Customer  {

    CONST TOKEN = "123456wc";

    public function index(){
        if (isset($_GET['echostr'])) {          //校验服务器地址URL
            $this->valid();
        }else{
           $this->responseMsg();
        }    
    }

    public function valid(){
        $token = self::TOKEN;
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            header('content-type:text');
            echo $echoStr;
            exit;
        }else{
            echo $echoStr.'+++'.$token;
            exit;
        }
    }

   private function checkSignature()
    {
        $token = self::TOKEN;
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
    
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }


    public function responseMsg()
    {
        $postStr = file_get_contents('php://input');
        //$postArrs = json_decode($postStr,true);
        $postArrs = xml_to_array($postStr);
        
        if($postArrs['MsgType'] == 'text'){
            if($postArrs['Content'] == '客服'){
                echo "<xml><ToUserName><![CDATA[".$postArrs['FromUserName']."]]></ToUserName><FromUserName><![CDATA[".$postArrs['ToUserName']."]]></FromUserName><CreateTime>".$postArrs['CreateTime']."</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>";
                $content = '正在转接客服，请稍等';                 //修改为自己需要的文字
                $data = array(
                    "touser"    => $postArrs['FromUserName'],
                    "msgtype"   => "text",
                    "text"      => ['content' => $content],
                );
                $json = json_encode($data, JSON_UNESCAPED_UNICODE);
                $this->requestAPI($json);
            }else{
                $content = CustomerModel::where('keyword', $postArrs['Content'])->value('content');
                if($content){
                    $data = array(
                        "touser"    => $postArrs['FromUserName'],
                        "msgtype"   => "text",
                        "text"      => ['content' => $content],
                    );
                    $json = json_encode($data, JSON_UNESCAPED_UNICODE);
                    $this->requestAPI($json);
                }
                    
            }
        }
    }
    


    function requestAPI($json){
        $access_token = $this->get_accessToken();
        /* 
         * POST发送https请求客服接口api
         */
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        //以'json'格式发送post的https请求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($json)){
            curl_setopt($curl, CURLOPT_POSTFIELDS,$json);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        if($output == 0){
            echo 'success';exit;
        }
    }       
    /* 调用微信api，获取access_token，有效期7200s*/
   public function get_accessToken()
   {
        $appid = app()->env->get('applet_app_id');
        $secret = app()->env->get('applet_app_secret'); // 小程序 app_secret
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"; //替换成自己的小程序id和secret
        @$weixin = file_get_contents($url);
        @$jsondecode = json_decode($weixin);
        @$array = get_object_vars($jsondecode);
        $token = $array['access_token'];
        return $token;
    }
}